<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="用户名称">
          <el-input
            v-model="searchParam.firstName"
            placeholder="请输入用户名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="供应商">
          <el-select
            v-model="searchParam.partnerId"
            placeholder="请选择供应商"
            clearable
          >
            <el-option
              v-for="item in partnerList"
              :key="item.id"
              :value="item.id"
              :label="item.partnerName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="searchParam.mobile"
            placeholder="请输入手机号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        >
        <!-- <el-button type="success" @click="excelBoxOpen">导入 </el-button>
        <el-dialog  :close-on-click-modal="false" title="用户信息数据导入" v-model="excelBox" width="555px">
          <div>
            <el-button
              @click="
                useDownload(
                  '/srm/partner/user/exportTemp',
                  '用户信息上传模板',
                  searchParam
                )
              "
            >
              <template #icon>
                <i-ep-download />
              </template>
              用户信息上传模板下载
            </el-button>
          </div>
          <div style="margin-top: 10px">
            <input
              class="crop-input"
              type="file"
              name="image"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              ref="onload_exl"
              @change="getfilepath"
            />
            <el-button
              @click="upload"
              :disabled="uploadBtn"
              style="cursor: pointer"
              >上传</el-button
            >
          </div>
        </el-dialog> -->
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          :prop="item.prop"
          :label="item.label"
          v-for="item in tableHeader"
          :key="item.prop"
          :sortable="item?.sort"
          :width="item.width"
          :align="item.align"
          show-overflow-tooltip
        >
          <template v-if="item.prop === 'partnerId'" #default="scope">
            {{ partnerNameFilter(scope.row.partnerId) }}
          </template>
          <template v-if="item.prop === 'enabled'" #default="scope">
            <el-tag v-if="scope.row.enabled === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="240" align="center">
          <template #default="scope">
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="重置密码"
              placement="top"
            >
              <el-button size="small" link @click="resetPsw(scope.row)">
                <i-ep-setting />
              </el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="编辑"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialog(scope.row)"
                ><i-ep-edit
              /></el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="删除"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="handleTableDelete(scope.row.id)"
                ><i-ep-delete
              /></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <srmuser-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "PARTNERSRMUSER",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/srm/partner/user/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  firstName: "",
  lastName: "",
  partnerId: "",
  mobile: "",
};

const deleteParam = {
  api: "/srm/partner/user/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

const tableHeader = [
  {
    prop: "loginName",
    label: "登录名称",
  },
  {
    prop: "firstName",
    label: "用户姓名",
  },
  {
    prop: "partnerId",
    label: "所属供应商",
  },
  {
    prop: "mobile",
    label: "手机号",
  },
  {
    prop: "createTime",
    label: "注册日期",
    align: "center",
    width: 160,
  },
  {
    prop: "enabled",
    label: "是否启用",
    align: "center",
    width: 100,
  },
];

let partnerList = ref([]);
async function getPartnerList() {
  const data = await request({
    url: "/srm/core/mdmpartner/getList",
    method: "post",
    data: {},
  });
  partnerList.value = data.data;
}

function resetPsw(data) {
  ElMessageBox.confirm("是否确定要为此供应商用户重置密码吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info",
    center: true,
  })
    .then(() => {
      request({
        url: "/srm/partner/user/resetPwd/",
        method: "post",
        data: data,
      }).then((data) => {
        ElMessage.success("密码重置成功");
      });
    })
    .catch(() => {
      return;
    });
}

onMounted(() => {
  getPartnerList();
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/srm/partner/user/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开用户信息表单弹窗 */
function openDialog(roleObj?: Object) {
  addDialog.visible = true;
  if (roleObj) {
    addDialog.title = "修改供应商用户信息";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增供应商用户信息";
    addDialog.data = {};
  }
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
}

// 导入excel
const uploadApi = "/srm/partner/user/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });

      excelBox.value = false;
      uploadBtn.value = true;
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}

function partnerNameFilter(partnerId: String) {
  let partner = partnerList.value.find((item) => {
    return item.id === partnerId;
  });
  return partner ? partner.partnerName : "";
}
</script>
